require 'erubis'
require 'rubygems'
require 'qingcloud/sdk'
require 'pp'
require 'time'
require 'yaml'
require 'thread'
require 'depac-common/utils'

module Depac
  class QCMgr
  
     private
     
     def initialize(cloud_credentials)
       access_key = cloud_credentials['access_key']
       secret_key = cloud_credentials['secret_key']
       @connector = QingCloud::SDK::Client::Connector.init(access_key, secret_key)      
       @service = QingCloud::SDK::Client::Service.new @connector  
       
       @lock = Mutex.new    
       
       #{:image_id=>"centos66x64a", :instance_type=>"c1m1", :cpu=>nil, :memory=>nil, :count=>1, :instance_name=>"test123", :login_mode=>"passwd", :login_keypair=>nil, :login_passwd=>"Passw0rd!", :vxnets_N=>["vxnet-jg716a6"], :security_group=>nil, :volumes_N=>[], :need_newsid=>nil, :need_userdata=>nil, :userdata_type=>nil, :userdata_value=>nil, :userdata_path=>nil, :zone=>"pek2"}
       
       @run_inst_params= {
                  image_id: nil,
                  instance_type: nil,
                  cpu: nil,
                  memory: nil,
                  count: 1,
                  instance_name: nil,
                  login_mode: nil,
                  login_keypair: nil,
                  login_passwd: 'Passw0rd!',
                  vxnets_N: nil,
                  security_group: nil,
                  volumes_N: [],
                  need_newsid: nil,
                  need_userdata: nil,
                  userdata_type: nil,
                  userdata_value: nil,
                  userdata_path: nil,
                  zone: nil
                 } 
                 
       @des_inst_params= {
                 instances_N: nil,
                 zone: nil       
       }  
       
       #service.add_load_balancer_backends(loadbalancer_listener: 'lbl-tbi6eqt2', backends_N_resource_id: ['192.168.110.26'], backends_N_loadbalancer_backend_name: ['192.168.110.26'], backends_N_port: ['8080'], backends_N_weight: [1], listeners_N_listener_option: [], zone: 'pek2')
       @add_lb_backend_params={
         loadbalancer_listener: nil,
         backends_N_resource_id: [],
         backends_N_loadbalancer_backend_name: [],
         backends_N_port: ['8080'],  
         backends_N_weight: [1], 
         listeners_N_listener_option: [],
         zone: 'pek2'
       }
       
       #modify_load_balancer_backend_attributes(loadbalancer_backend:, port: nil, weight: nil, disabled: nil, loadbalancer_policy_id: nil, zone:)
       @modify_lb_backend_params={
            loadbalancer_backend: nil,
            port: '8080',
            weight: 1,
            disabled: nil,
            loadbalancer_policy_id: nil,
            zone: 'pek2'        
       }
       
       #delete_load_balancer_backends(loadbalancer_backends_N: [], zone:)
       @delete_lb_backend_params={
	  		loadbalancer_backends_N: [],
	  		zone: 'pek2'
	     }
     end
     
     def addLbBackend_internal(addLbBackendParaHash)
          #puts addLbBackendParaHash
               @service.add_load_balancer_backends addLbBackendParaHash
               return  @service.response
     end
     
     def deleteLbBackend_internal(deleteLbBackendParaHash)
    	      @service.delete_load_balancer_backends deleteLbBackendParaHash
	      	  return @service.response
     end
     
     #response for multi instance delete: {"action"=>"TerminateInstancesResponse", "job_id"=>"j-p2w8o1if", "ret_code"=>0}
     def deleteInstance_internal(deleteInstParaHash)
             #@service.terminate_instances instances_N: ['i-mrzjql3h'], zone: 'pek2'
             @service.terminate_instances deleteInstParaHash
             return  @service.response
     end
     
     def modifyLbBackend_internal(modifyLbBackendParaHash)
               #puts modifyLbBackendParaHash
               Depac::Log.write("INFO", "qingcloud.modifyLbBackend_internal: #{modifyLbBackendParaHash}") 
               @service.modify_load_balancer_backend_attributes modifyLbBackendParaHash
               return  @service.response
     end
     
     public
     
     def addLbBackend(addBackendParaHash)
       
       lb_backendID=nil
       
       _addBackendParaHash=@add_lb_backend_params.clone            
       _addBackendParaHash.merge! addBackendParaHash 
       Depac::Log.write("INFO", "qingcloud.addLBackend: after merge with defaule parameter hash: #{_addBackendParaHash}.......")
       
       @service.describe_load_balancer_backends(loadbalancer_listener: addBackendParaHash[:loadbalancer_listener], zone: 'pek2')
       response_backend_list = @service.response['loadbalancer_backend_set']
       Depac::Log.write("INFO", "check existed loadbalance backend list: #{response_backend_list}  ")
       ip_port = Hash.new
       
       response_backend_list.each do |item| 
           ip_port.store(item['resource_id']+"-"+item['port'].to_s,nil )
       end
       
       id_tmp = _addBackendParaHash[:backends_N_resource_id]
       id_tmp_port = _addBackendParaHash[:backends_N_port]
       Depac::Log.write("INFO", "canditate backend resource is: #{id_tmp} with port #{id_tmp_port}")
         
       if ip_port.size >0 && ip_port.has_key?(id_tmp[0]+"-"+id_tmp_port[0])
                Depac::Log.write("INFO", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
              
                Depac::Log.write("INFO", "#{id_tmp[0]} has existed under listener #{addBackendParaHash[:loadbalancer_listener]} with port #{id_tmp_port} ")   
       else
             Depac::Log.write("INFO", "call addLBBackend_internal to add Loadbalance backend..........")
             response=addLbBackend_internal(_addBackendParaHash)
             
             lb_backendID=response['loadbalancer_backends'][0]
             
             Depac::Log.write("INFO", "#{id_tmp[0]} has been added to listener #{addBackendParaHash[:loadbalancer_listener]} with backendID #{lb_backendID}")
       end
       
       return lb_backendID
     end
     
     def deleteLbBackend(listenerID,ipAddress)
	    _deleteLbBackendParaHash=@delete_lb_backend_params
	    @service.describe_load_balancer_backends(loadbalancer_listener: listenerID, zone: 'pek2')
		  #Depac::Log.write("INFO", "response: #{@service.response['loadbalancer_backend_set']}")
		  Depac::Log.write("INFO", "Backend IP to be delete: #{ipAddress}")  
		  @service.response['loadbalancer_backend_set'].each do |item|
		    if item['resource_id'] == ipAddress
		      _deleteLbBackendParaHash[:loadbalancer_backends_N][0] = item['loadbalancer_backend_id']
		      Depac::Log.write("INFO", "LoadBalanceBackendID: #{_deleteLbBackendParaHash[:loadbalancer_backends_N][0]}") 
		      deleteLbBackend_internal(_deleteLbBackendParaHash)
		    end
		  end  
     end
     
     
     def deleteInstance(deleteInstParaHash)      
               _deleteInstParaHash=@des_inst_params.clone            
               _deleteInstParaHash.merge! deleteInstParaHash     
               Depac::Log.info("depac.qingcloud.deleteInstance: final param hash is : #{_deleteInstParaHash}")      
               response=deleteInstance_internal(_deleteInstParaHash)
     end
     
     def modifyLbBackends(modifyBackendParaHash)
     
         Depac::Log.write("INFO", "LoadBalanceBackendID: #{modifyBackendParaHash[:loadbalancer_backend]}") 
         _modifyBackendParaHash=@modify_lb_backend_params.clone
         _modifyBackendParaHash.merge! modifyBackendParaHash
         
         Depac::Log.write("INFO", "qingcloud.modifyLbbakends.finial.parameters: #{_modifyBackendParaHash}") 
         modifyLbBackend_internal(_modifyBackendParaHash)

     end
     
     def provisionVMs(envConfig, envName, buildLabel, hn_counter, existenvConfig)    
     
          #this method used to verify the image
          #1. if not set the srcimagedid, scripts will try to load role_image_mapping.yml to find the default image
          #2. if set image, scripts will try to check if this image already existed.
          #buildAndValidateImageNames(newEnvConfigObj, buildLabel)   
          
         Depac::Utils.ensureKeys(Depac::CloudDeploymentConstants::CLD_DPL_KEYPATH, "cloud-deployment-workspace-key")
          
         Depac::Log.info(Depac::CloudDeploymentConstants::BORDER_LINE)
          
         startProvisionTime = Time.new            
         
         nodeInfoMap = Hash.new
         
         envConfig[:vms].each do |roleconfig|
             role = roleconfig[Depac::CloudDeploymentConstants::ROLE]
             vmconfig = roleconfig['vmconfig']
             
             if roleconfig[Depac::CloudDeploymentConstants::ROLE].include?('shadow') # will not provision shadow node
                next
             end
               
             if(vmconfig == nil)
					        Depac::Log.write("INFO", Depac::CloudDeploymentConstants::BORDER_LINE)
					        Depac::Log.write("ERROR", "vmconfig for the role - #{role} is missing")
					        exit
		         end
         
            
         
         #if (role.include?"db" || role.include?"mq")
			   #config[Depac::CloudDeploymentConstants::NO_OF_NODES]=1
		     #end	 
		 
		     Depac::Log.write("INFO", "Provisioning #{role}")
		 
		     nodeCount = 0
		     if(hn_counter!=0)
			     nodeCount=hn_counter-1
		     elsif(existenvConfig != nil)
			      nodeCount = getNodeCountFromExistingEnv(existenvConfig.getNodeConfigurationByRoleAndType(role, type))
		     end
		     
		     roleconfig[Depac::CloudDeploymentConstants::NO_OF_NODES] =1 unless roleconfig[Depac::CloudDeploymentConstants::NO_OF_NODES]		       
		 
		     Depac::Log.write("INFO", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>start generate hostnameAtt")
		     hostnameArr = Utils.getHostnames(buildLabel, envName, 'QC', role, roleconfig[Depac::CloudDeploymentConstants::NO_OF_NODES], nodeCount)	
		     Depac::Log.write("INFO", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>finish generate hostnameAtt")
		     
		     
		     Depac::Log.write("INFO", "#{role} hostname(s):  #{hostnameArr}")
		     Depac::Log.write("INFO", Depac::CloudDeploymentConstants::EMPTY_STRING)
		
		     hostnameIPArr = Array.new
			 
			   threads = []
			
		     hostnameArr.each do |hostname|
		     	
		      #provisioning the vm 
				  Depac::Log.info("Provisioning server from snapshot with hostname #{hostname}")
				
				  params_Map=generateParamsMap(@run_inst_params, roleconfig['vmconfig'], hostname)
				
				  Depac::Log.write("INFO", "Generated params hash is : #{params_Map}") 
				  
			    instanceInfo= provisionInstance(params_Map)
			    
			    Depac::Log.write("INFO", "provisionInstance: #{instanceInfo}.............")
			    Depac::Log.write("INFO", "waiting to check vm transaction complete.............")
			    
			    hostnameIPMap = Hash.new
			    hostnameIPMap['hostname'] = hostname
			      
			    if roleconfig['chefroles'] !=nil
               hostnameIPMap['chefnodename'] = hostname
               hostnameIPMap['chefroles'] = roleconfig['chefroles'] 
			    end
			    
			    hostnameIPMap['vmid'] = instanceInfo['instances'][0]
			    hostnameIPMap['IP'] = nil	
			    
			    #set default value to each node first
			    Depac::Log.write("INFO", "setting war/linkto/schema default value to #{hostname}.............")		    
			    hostnameIPMap['wars'] = roleconfig['wars'] if role.include?("app") && roleconfig['wars'] != nil
			    hostnameIPMap['linkto'] = roleconfig['linkto'] if roleconfig["linkto"] !=nil
			    hostnameIPMap['schema'] = roleconfig['schema'] if role.include?("db") && roleconfig['schema'] !=nil
			      
			    #for promotion
			    hostnameIPMap['components']	= roleconfig['components'] if roleconfig["components"] !=nil
			      
			    #for LB register
			    hostnameIPMap['lb_backend_Config']	= roleconfig['lb_backend_Config'] if roleconfig['lb_backend_Config'] !=nil  
			    
			    #for docker
			    hostnameIPMap['reversproxy'] = roleconfig['reversproxy'] if roleconfig['reversproxy'] !=nil
          hostnameIPMap['etcd'] = roleconfig['etcd'] if roleconfig['etcd'] !=nil
          hostnameIPMap['no_of_inst'] = roleconfig['no_of_inst'] if roleconfig['no_of_inst'] != nil
            
            
          #for mongo sharding
          hostnameIPMap['shardconfig'] = roleconfig['shardconfig'] if roleconfig['shardconfig'] !=nil
			    
			    hostnameIPArr.push(hostnameIPMap)
			    Depac::Log.write("INFO", Depac::CloudDeploymentConstants::BORDER_LINE)
			    
		    end
		    
		    hostnameIPArr.each do |hostnameIPMap|
		    
		        threads << Thread.new(hostnameIPMap) {
                     private_ip=waitForVMTransactionsToComplete(Array.new.push(hostnameIPMap['vmid']), roleconfig['vmconfig'][:zone]) 
                     #instanceDescribe=describeInstance(Array.new.push(hostnameIPMap['vmid'], roleconfig['vmconfig'][:zone])
                     # modifications to the vms_withinfo object is not thread safe
                     @lock.synchronize do
                        hostnameIPMap['IP']=private_ip
                     end
                }
                	
            end       
			    
		    threads.each { |aThread| aThread.join }
		    
		    nodeInfoMap[role] = hostnameIPArr	     
		  end  	  
		  return nodeInfoMap  
     end  
     
     
     def getInstanceIPFromDescribeByIndex(describeResponse, index)
     
          instanceInfo=describeResponse['instance_set'][index]
          Depac::Log.write("INFO", "Instance info: #{instanceInfo}")
          vxnetInfo=instanceInfo['vxnets'][0]
          
          return vxnetInfo['private_ip'] 
          Depac::Log.write("INFO", "get private_ip : #{vxnetInfo['private_ip']}") 
     end
     
     def getInstanceIPFromDescribeByInstanceID()
     end
     
     
     def generateParamsMap(paramsDefine, vmconfig, hostname)
     
          paramsDefine_clone=paramsDefine.clone       
          vmconfig.each_key do |key|
          
               paramsDefine_clone[key]= vmconfig[key]          
          end  
          
           paramsDefine_clone[:instance_name] = hostname    
          return paramsDefine_clone
     end
     
     #response for one instance {"action"=>"RunInstancesResponse", "instances"=>["i-ip2gwrzs"], "job_id"=>"j-zm8zm0c6", "ret_code"=>0}
     #response for multi instance {"action"=>"RunInstancesResponse", "instances"=>["i-rbd01srn", "i-jsjjpabp"], "job_id"=>"j-zg1g0o0s", "ret_code"=>0}
     
     #def run_instances(image_id:, instance_type: nil, cpu: nil, memory: nil, count: 1, instance_name: nil, login_mode:, login_keypair: nil, login_passwd: nil, vxnets_N: [], security_group: nil, volumes_N: [], need_newsid: nil, need_userdata: nil, userdata_type: nil, userdata_value: nil, userdata_path: nil,  zone:)eval(build_fetch_match)
     #end
     #def provisionInstance(run_inst_params)
     #     service.run_instances image_id: 'centos66x64a', 
     #                 instance_type: 'c1m1',
     #                 login_mode: 'passwd', 
     #                 login_passwd: 'Passw0rd!',
     #                vxnets_N: ['vxnet-jg716a6'],                      
     #                 zone: 'pek2'                     
     #     puts service.response  
     #end
     def provisionInstance(run_inst_params)
          @service.run_instances run_inst_params               
          return  @service.response  
     end
     
     def waitForVMTransactionsToComplete(vmids, zone)
           
           Log.write("INFO","From qingcloud.rb.waitForVMTransactionsToComplete: vmids->#{vmids} zone->#{zone}")
           private_ip = nil
                  
           describInfo= describeInstance(vmids, zone)
           vmstatue=(describInfo['instance_set'][0])['status']
           #Log.write("INFO","From qingcloud.rb.waitForVMTransactionsToComplete: First describInfo--> #{describInfo}")
           
           Log.write("INFO","Current  #{vmids} status: #{vmstatue}")
           while(describInfo !=nil && vmstatue != "running")
                  Log.write("INFO","waiting for #{vmids} running ! sleep 2 s")
                  sleep 2
                  describInfo= describeInstance(vmids, zone)
                  vmstatue=(describInfo['instance_set'][0])['status']
                  Log.write("INFO","Current  #{vmids} status: #{vmstatue}")
           end
           Log.write("INFO","VM #{vmids} is running ! waiting IP ready>>>>>>>>>>>>>>>>>>>>>>>")
           
           vmInfo= describInfo['instance_set'][0]
           Log.write("INFO","From qingcloud.rb.waitForVMTransactionsToComplete: First vminfo--> #{vmInfo}")
           
           vxnet= vmInfo['vxnets'][0]
           Log.write("INFO","From qingcloud.rb.waitForVMTransactionsToComplete: First vxnet--> #{vxnet}")
           
           private_ip=vxnet['private_ip']                     
           
           while(describInfo !=nil && private_ip == nil)
               Log.write("INFO","Waiting #{vmids} IP ready, sleep 2 s")
               sleep 2
               describInfo= describeInstance(vmids, zone)
               vmInfo= describInfo['instance_set'][0]
               vxnet= vmInfo['vxnets'][0]          
               private_ip=vxnet['private_ip']
               
               #Log.write("INFO","Current  #{vmids} status: #{vmStatus}")
           end
           
           Log.write("INFO","#{vmids} create transaction complete get private_ip : #{private_ip} !")
           return private_ip
     end
     
     
     #response for one instance 
     #{"action"=>"DescribeInstancesResponse", "instance_set"=>[{"vcpus_current"=>1, "status"=>"running", "vxnets"=>[{"vxnet_name"=>"ManagementVlan_devops", "vxnet_type"=>1, "vxnet_id"=>"vxnet-jg716a6", "nic_id"=>"52:54:58:61:ba:22", "private_ip"=>"192.168.110.21"}], "memory_current"=>1024, "cpu_topology"=>"", "lastest_snapshot_time"=>"", "sub_code"=>0, "transition_status"=>"", "instance_id"=>"i-rbd01srn", "instance_type"=>"c1m1", "instance_class"=>0, "dns_aliases"=>[], "create_time"=>"2015-06-16T04:27:15Z", "owner"=>"usr-jyckCtDn", "status_time"=>"2015-06-16T04:27:15Z", "alarm_status"=>"", "instance_name"=>"", "image"=>{"ui_type"=>"tui", "processor_type"=>"64bit", "platform"=>"linux", "image_size"=>20, "image_name"=>"CentOS 6.6 64bit", "image_id"=>"centos66x64a", "os_family"=>"centos", "provider"=>"system"}, "description"=>nil}], "total_count"=>1, "ret_code"=>0}
     
     #response for mutil instance will be a hashmap in instance_set
     #{"action"=>"DescribeInstancesResponse", "instance_set"=>[{"vcpus_current"=>1, "status"=>"running", "vxnets"=>[{"vxnet_name"=>"ManagementVlan_devops", "vxnet_type"=>1, "vxnet_id"=>"vxnet-jg716a6", "nic_id"=>"52:54:58:61:ba:22", "private_ip"=>"192.168.110.21"}], "memory_current"=>1024, "cpu_topology"=>"", "lastest_snapshot_time"=>"", "sub_code"=>0, "transition_status"=>"", "instance_id"=>"i-rbd01srn", "instance_type"=>"c1m1", "instance_class"=>0, "dns_aliases"=>[], "create_time"=>"2015-06-16T04:27:15Z", "owner"=>"usr-jyckCtDn", "status_time"=>"2015-06-16T04:27:15Z", "alarm_status"=>"", "instance_name"=>"", "image"=>{"ui_type"=>"tui", "processor_type"=>"64bit", "platform"=>"linux", "image_size"=>20, "image_name"=>"CentOS 6.6 64bit", "image_id"=>"centos66x64a", "os_family"=>"centos", "provider"=>"system"}, "description"=>nil}, {"vcpus_current"=>1, "status"=>"running", "vxnets"=>[{"vxnet_name"=>"ManagementVlan_devops", "vxnet_type"=>1, "vxnet_id"=>"vxnet-jg716a6", "nic_id"=>"52:54:0e:51:96:94", "private_ip"=>"192.168.110.20"}], "memory_current"=>1024, "cpu_topology"=>"", "lastest_snapshot_time"=>"", "sub_code"=>0, "transition_status"=>"", "instance_id"=>"i-jsjjpabp", "instance_type"=>"c1m1", "instance_class"=>0, "dns_aliases"=>[], "create_time"=>"2015-06-16T04:27:11Z", "owner"=>"usr-jyckCtDn", "status_time"=>"2015-06-16T04:27:11Z", "alarm_status"=>"", "instance_name"=>"", "image"=>{"ui_type"=>"tui", "processor_type"=>"64bit", "platform"=>"linux", "image_size"=>20, "image_name"=>"CentOS 6.6 64bit", "image_id"=>"centos66x64a", "os_family"=>"centos", "provider"=>"system"}, "description"=>nil}], "total_count"=>2, "ret_code"=>0}
     
     def describeInstance(vms, zone)     
          Log.write("INFO","describeInstance: #{vms} on zone #{zone}")     
          @service.describe_instances instances_N: vms, zone: zone
          return  @service.response        
     end
     
     
     #response for multi instance start: {"action"=>"StartInstancesResponse", "job_id"=>"j-lbmxk7t2", "ret_code"=>0}
     def startInstance_internal(vms)
          @service.start_instances instances_N: ['i-7td25mrr'], zone: 'pek2'
          return  @service.response
          
     end
     
     #response for multi instance stop: {"action"=>"StopInstancesResponse", "job_id"=>"j-x27ivvjf", "ret_code"=>0}
     def stopInstance(vms)
           @service.stop_instances instances_N: ['i-7td25mrr'], zone: 'pek2'
           return  @service.response
     end
     
     #loadbalancers_N is array object
     #listenerID is string
     #{"action"=>"DescribeLoadBalancerListenersResponse", "total_count"=>1, "loadbalancer_listener_set"=>[{"forwardfor"=>0, "listener_option"=>0, "listener_protocol"=>"http", "server_certificate_id"=>"", "backend_protocol"=>"http", "healthy_check_method"=>"tcp", "session_sticky"=>"", "loadbalancer_listener_name"=>"", "disabled"=>0, "balance_mode"=>"roundrobin", "create_time"=>"2015-07-08T06:58:30Z", "healthy_check_option"=>"10|5|2|5", "timeout"=>50, "owner"=>"usr-jyckCtDn", "loadbalancer_listener_id"=>"lbl-tbi6eqt2", "loadbalancer_id"=>"lb-0nawr55f", "listener_port"=>8081}], "ret_code"=>0}
     def applyLBChange(loadbalancers_N, listenerID, zone="pek2")
       #update_load_balancers(loadbalancers_N:, zone:) ⇒ Object
       Depac::Log.write("INFO", "qingcloud.applyLBChange.....................................")               
       if loadbalancers_N !=nil && loadbalancers_N.size >0
         Depac::Log.write("INFO", "qingcloud.applyLBChange using loadbalancers_N #{loadbalancers_N}.....................................") 
         @service.update_load_balancers(loadbalancers_N: loadbalancers_N , zone: zone)
         response=@service.response
         Log.write("INFO","qingcloud.applyLBChange.response: #{response}")
       elsif listenerID !=nil
         Depac::Log.write("INFO", "qingcloud.applyLBChange using listenerID #{listenerID}.....................................") 
         @service.describe_load_balancer_listeners(loadbalancer_listeners_N: [listenerID], zone: zone)
         describe_ListenersSet= @service.response
         if describe_ListenersSet!=nil
               loadbalancerListener=(describe_ListenersSet['loadbalancer_listener_set'])[0]
               loadbalancer_id=loadbalancerListener['loadbalancer_id']
               Depac::Log.write("INFO", "qingcloud.applyLBChange detected loadbalancer id is  #{loadbalancer_id}.....................................") 
               if loadbalancer_id !=nil
                          @service.update_load_balancers(loadbalancers_N: [loadbalancer_id] , zone: zone)
                          response=@service.response
                          Log.write("INFO","qingcloud.applyLBChange.response: #{response}")
               end
         else
             Log.write("INFO","qingcloud.applyLBChange: can not find target loadbalancers!")
         end

       else
          Log.write("INFO","qingcloud.applyLBChange: input invalid! ignore this action!")  
       end
       
     end
     
     #1--disable
     #0--enable
     def backendDisable?(backendID, disable=1, zone='pek2')
          
       modifyBackendParaHash={
            loadbalancer_backend: backendID,           
            disabled: disable,
            zone: zone        
       }
       Depac::Log.info("qingcloud.backendDisable: offline LB backend #{backendID}.........")
       @service.modify_load_balancer_backend_attributes modifyBackendParaHash
       
       @service.response
      
       @service.describe_load_balancer_backends(loadbalancer_backends_N: [backendID], zone: zone)
       lb_backend_sets=(@service.response)['loadbalancer_backend_set']
         
       loadbalancersIDs=Array.new
       
       if lb_backend_sets!=nil
         
         lb_backend_sets.each do |lb_backend_obj|
           loadbalancersIDs.push(lb_backend_obj['loadbalancer_id'])
         end
         
       end
       
       loadbalancersIDs.uniq!
       
       applyLBChange(loadbalancersIDs, nil, zone)
     end
     
  end
end 